from flask import Flask, jsonify, render_template_string, request
from flask_cors import CORS
from device_connector import MockDeviceConnector
from real_device_connector import SimpleDeviceConnector
from enhanced_data_processor import EnhancedDataProcessor, DataStorage
from device_controller import command_sender
import yaml
import threading
import time
import os

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 真实设备配置（使用HTTP API方式）
ACCESS_KEY_ID = "LTAI5tLaEL25ZmTmQDsLgXmp"
ACCESS_KEY_SECRET = "4okDqudOGjvgngiCzzf5UQqQSZ1AbV"

SPARK_CONFIG = {
    'access_key_id': ACCESS_KEY_ID,
    'access_key_secret': ACCESS_KEY_SECRET,
    'product_key': 'k29cquyln1r',
    'device_name': 'Spark',
    'region': 'cn-shanghai'
}

MONITOR_CONFIG = {
    'access_key_id': ACCESS_KEY_ID,
    'access_key_secret': ACCESS_KEY_SECRET,
    'product_key': 'k29cquyln1r',
    'device_name': 'monitor',
    'region': 'cn-shanghai'
}

# 全局变量存储设备连接器
devices = {}
latest_data = {}

# 创建增强型数据处理器和存储器
data_processor = EnhancedDataProcessor()
data_storage = DataStorage()

def load_device_config():
    """加载设备配置"""
    config_path = 'config/devices.yaml'
    try:
        with open(config_path, 'r', encoding='utf-8') as file:
            return yaml.safe_load(file)
    except Exception as e:
        print(f"配置文件加载失败: {e}")
        return {'devices': []}

def initialize_devices():
    """初始化设备连接器"""
    global devices
    
    print("🔗 初始化真实设备连接器...")
    # 初始化真实设备连接器
    devices['spark'] = SimpleDeviceConnector(
        SPARK_CONFIG['access_key_id'],
        SPARK_CONFIG['access_key_secret'],
        SPARK_CONFIG['product_key'],
        SPARK_CONFIG['device_name'],
        SPARK_CONFIG['region']
    )
    devices['monitor'] = SimpleDeviceConnector(
        MONITOR_CONFIG['access_key_id'],
        MONITOR_CONFIG['access_key_secret'],
        MONITOR_CONFIG['product_key'],
        MONITOR_CONFIG['device_name'],
        MONITOR_CONFIG['region']
    )
    print(f"✅ 真实设备连接器已初始化")
    
    # 备用模拟设备（用于测试）
    config = load_device_config()
    devices_config = config.get('devices', {})
    
    # 处理字典格式的设备配置
    if isinstance(devices_config, dict):
        for device_id, device_config in devices_config.items():
            if device_id not in devices:
                devices[device_id] = MockDeviceConnector(device_config)
    # 处理列表格式的设备配置（向后兼容）
    elif isinstance(devices_config, list):
        for device_config in devices_config:
            device_name = device_config.get('name', 'unknown')
            if device_name not in devices:
                devices[device_name] = MockDeviceConnector(device_config)
    
    print(f"设备初始化完成: {len(devices)} 个设备")

def collect_data():
    """数据收集线程 - 使用增强型数据处理器"""
    global latest_data
    
    while True:
        try:
            # 收集Spark设备数据
            if 'spark' in devices:
                spark_data = devices['spark'].fetch_data()
                if spark_data:
                    print(f"📊 Spark设备数据: {len(spark_data)} 个属性")
                    data_processor.update_device_data('spark', spark_data)
            
            # 收集Monitor设备数据
            if 'monitor' in devices:
                monitor_data = devices['monitor'].fetch_data()
                if monitor_data:
                    print(f"📊 Monitor设备数据: {len(monitor_data)} 个属性")
                    data_processor.update_device_data('monitor', monitor_data)
            
            # 获取处理后的数据
            processed_data = data_processor.get_processed_data()
            if processed_data:
                # 存储到数据库
                data_storage.save_data(processed_data)
                
                # 更新最新数据（用于API响应）
                latest_data = data_processor.get_categorized_data()
                
                print(f"💾 数据已处理并存储: 心率={processed_data.get('heart_rate', 0)}, 温度={processed_data.get('temperature', 0)}")
            
            # 收集其他模拟设备数据（向后兼容）
            for device_name, connector in devices.items():
                if device_name not in ['spark', 'monitor']:
                    data = connector.fetch_data()
                    if data:
                        # 将模拟设备数据也存入latest_data
                        latest_data[device_name] = data
            
        except Exception as e:
            print(f"❌ 数据收集错误: {e}")
        
        time.sleep(5)  # 每5秒收集一次

# API端点

@app.route('/api/adjust-bed', methods=['POST'])
def adjust_bed():
    """调整床板位置"""
    try:
        data = request.json
        device_name = data.get('device_name', 'Spark')
        product_key = data.get('product_key', 'k29cquyln1r')
        angle = data.get('angle', 0)
        speed_level = data.get('speed_level', 2)  # 默认正常速度
        
        # 发送指令
        success, message = command_sender.send_bed_command(
            device_name, product_key, angle, speed_level
        )
        
        if success:
            return jsonify({'status': 'success', 'message': message})
        return jsonify({'status': 'error', 'message': message}), 400
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

@app.route('/api/reset-bed', methods=['POST'])
def reset_bed():
    """复位床板位置"""
    try:
        data = request.json
        device_name = data.get('device_name', 'Spark')
        product_key = data.get('product_key', 'k29cquyln1r')
        
        # 发送复位指令（角度0，正常速度）
        success, message = command_sender.send_bed_command(
            device_name, product_key, 0, 2
        )
        
        if success:
            return jsonify({'status': 'success', 'message': message})
        return jsonify({'status': 'error', 'message': message}), 400
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

@app.route('/api/vitals')
def vitals_data():
    """获取人体生命体征数据"""
    try:
        categorized_data = data_processor.get_categorized_data()
        return jsonify(categorized_data.get('vitals', {}))
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/environment')
def environment_data():
    """获取环境数据"""
    try:
        categorized_data = data_processor.get_categorized_data()
        return jsonify(categorized_data.get('environment', {}))
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/bed-status')
def bed_status():
    """获取床板状态数据"""
    try:
        categorized_data = data_processor.get_categorized_data()
        return jsonify(categorized_data.get('bed_status', {}))
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/sleep-analysis')
def sleep_analysis():
    """获取睡眠分析数据"""
    try:
        categorized_data = data_processor.get_categorized_data()
        return jsonify(categorized_data.get('sleep_analysis', {}))
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/all-data')
def all_data():
    """获取所有分类数据"""
    try:
        return jsonify(data_processor.get_categorized_data())
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/current-data')
def current_data():
    """获取当前所有设备数据（兼容旧接口）"""
    return jsonify(latest_data)

@app.route('/api/statistics')
def get_statistics():
    """获取数据库统计信息"""
    try:
        stats = data_storage.get_statistics()
        if stats:
            return jsonify({
                'total_records': stats[0],
                'avg_heart_rate': round(stats[1], 1) if stats[1] else 0,
                'avg_breath_rate': round(stats[2], 1) if stats[2] else 0,
                'avg_temperature': round(stats[3], 1) if stats[3] else 0,
                'latest_timestamp': stats[4]
            })
        else:
            return jsonify({'message': '暂无统计数据'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/bed-control', methods=['POST'])
def bed_control():
    """控制床板动作"""
    try:
        data = request.json
        device_id = data.get('device_id')
        action = data.get('action')
        params = data.get('params', {})
        
        if not device_id or not action:
            return jsonify({'error': '缺少设备ID或动作'}), 400
        
        # 查找设备连接器
        connector = devices.get(device_id)
        if not connector:
            return jsonify({'error': '设备未找到'}), 404
        
        # 发送控制命令
        command_sender.send_command(connector, action, params)
        
        return jsonify({'message': '命令已发送', 'device_id': device_id, 'action': action, 'params': params})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/')
def dashboard():
    """主仪表板页面"""
    return render_template_string("""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🛏️ 健康床监控系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Microsoft YaHei', Arial, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 35px rgba(0,0,0,0.15);
        }
        .card h3 {
            color: #4a5568;
            margin-bottom: 15px;
            font-size: 1.3em;
            border-bottom: 2px solid #edf2f7;
            padding-bottom: 8px;
        }
        .data-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            padding: 5px 0;
        }
        .data-label {
            color: #666;
            font-weight: 500;
        }
        .data-value {
            font-weight: bold;
            color: #2d3748;
        }
        .status-good { color: #38a169; }
        .status-warning { color: #d69e2e; }
        .status-error { color: #e53e3e; }
        .timestamp {
            text-align: center;
            color: #666;
            font-size: 0.9em;
            margin-top: 20px;
            padding: 10px;
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
        }
        .loading {
            text-align: center;
            color: white;
            font-size: 1.2em;
        }
        .raw-data {
            background: #f7fafc;
            border-radius: 10px;
            padding: 15px;
            margin-top: 15px;
            max-height: 200px;
            overflow-y: auto;
        }
        .raw-data pre {
            font-size: 0.8em;
            line-height: 1.4;
        }
        .control-card {
            background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
            color: #2d3436;
        }
        .control-card h3 {
            color: #2d3436;
            border-bottom-color: rgba(45, 52, 54, 0.2);
        }
        .range-input {
            width: 100%;
            margin: 10px 0;
        }
        .speed-buttons {
            display: flex;
            gap: 5px;
            margin: 10px 0;
        }
        .speed-btn {
            flex: 1;
            padding: 8px;
            border: none;
            border-radius: 5px;
            background: #74b9ff;
            color: white;
            cursor: pointer;
            transition: background 0.3s;
        }
        .speed-btn:hover {
            background: #0984e3;
        }
        .speed-btn.active {
            background: #00b894;
        }
        .control-btn {
            width: 100%;
            padding: 12px;
            margin: 5px 0;
            border: none;
            border-radius: 8px;
            background: #00cec9;
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.3s;
        }
        .control-btn:hover {
            background: #00a085;
        }
        .preset-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 5px;
            margin-top: 10px;
        }
        .preset-btn {
            padding: 6px;
            border: none;
            border-radius: 5px;
            background: #fd79a8;
            color: white;
            cursor: pointer;
            font-size: 0.9em;
            transition: background 0.3s;
        }
        .preset-btn:hover {
            background: #e84393;
        }
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-connected { background: #00b894; }
        .status-connecting { background: #fdcb6e; }
        .status-disconnected { background: #e17055; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🛏️ 健康床监控系统</h1>
            <p>实时监控睡眠质量与环境数据</p>
        </div>
        
        <div id="loading" class="loading">📡 正在加载数据...</div>
        
        <div id="dashboard" style="display: none;">
            <div class="grid">
                <div class="card">
                    <h3>🫀 生命体征</h3>
                    <div id="vitals-data"></div>
                </div>
                
                <div class="card">
                    <h3>🌡️ 环境监测</h3>
                    <div id="environment-data"></div>
                </div>
                
                <div class="card">
                    <h3>🛏️ 床板状态</h3>
                    <div id="bed-data"></div>
                </div>
                
                <div class="card">
                    <h3>😴 睡眠分析</h3>
                    <div id="sleep-data"></div>
                </div>
                
                <div class="card control-card">
                    <h3>🎛️ 床板控制</h3>
                    <div id="bed-control">
                        <div class="data-row">
                            <span class="data-label">连接状态:</span>
                            <span class="data-value">
                                <span id="connection-status" class="status-indicator status-disconnected"></span>
                                <span id="connection-text">未连接</span>
                            </span>
                        </div>
                        
                        <div class="data-row">
                            <span class="data-label">床板角度: <span id="angle-display">0</span>°</span>
                        </div>
                        <input type="range" id="angle-slider" class="range-input" min="0" max="90" step="1" value="0">
                        <div style="display: flex; justify-content: space-between; font-size: 0.8em; color: #666;">
                            <span>0°</span>
                            <span>45°</span>
                            <span>90°</span>
                        </div>
                        
                        <div class="data-row">
                            <span class="data-label">转动速度:</span>
                        </div>
                        <div class="speed-buttons">
                            <button class="speed-btn" data-speed="1">慢速</button>
                            <button class="speed-btn active" data-speed="2">正常</button>
                            <button class="speed-btn" data-speed="3">快速</button>
                        </div>
                        
                        <button class="control-btn" onclick="adjustBed()">🎯 调整床板</button>
                        <button class="control-btn" onclick="resetBed()">🔄 复位</button>
                        
                        <div class="data-row">
                            <span class="data-label">预设位置:</span>
                        </div>
                        <div class="preset-buttons">
                            <button class="preset-btn" onclick="applyPreset(45, 2)">📖 阅读</button>
                            <button class="preset-btn" onclick="applyPreset(30, 2)">📺 看电视</button>
                            <button class="preset-btn" onclick="applyPreset(15, 1)">😌 休息</button>
                            <button class="preset-btn" onclick="applyPreset(0, 3)">😴 平躺</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h3>📊 原始数据</h3>
                <div class="raw-data">
                    <pre id="raw-data"></pre>
                </div>
            </div>
        </div>
        
        <div class="timestamp" id="timestamp"></div>
    </div>

    <script>
        async function fetchData() {
            try {
                const response = await fetch('/api/all-data');
                const data = await response.json();
                
                document.getElementById('loading').style.display = 'none';
                document.getElementById('dashboard').style.display = 'block';
                
                updateVitalsDisplay(data.vitals || {});
                updateEnvironmentDisplay(data.environment || {});
                updateBedDisplay(data.bed_status || {});
                updateSleepDisplay(data.sleep_analysis || {});
                updateRawData(data);
                updateTimestamp();
                
            } catch (error) {
                console.error('数据获取失败:', error);
                document.getElementById('loading').innerHTML = '❌ 数据获取失败，正在重试...';
            }
        }
        
        function updateVitalsDisplay(vitals) {
            const container = document.getElementById('vitals-data');
            container.innerHTML = `
                <div class="data-row">
                    <span class="data-label">心率:</span>
                    <span class="data-value ${getHeartRateStatus(vitals.heart_rate)}">${vitals.heart_rate || '--'} bpm</span>
                </div>
                <div class="data-row">
                    <span class="data-label">呼吸率:</span>
                    <span class="data-value">${vitals.breath_rate || '--'} /min</span>
                </div>
                <div class="data-row">
                    <span class="data-label">人体存在:</span>
                    <span class="data-value">${vitals.body_exist ? '✅ 是' : '❌ 否'}</span>
                </div>
                <div class="data-row">
                    <span class="data-label">睡眠状态:</span>
                    <span class="data-value">${getSleepStateText(vitals.sleep_state)}</span>
                </div>
                <div class="data-row">
                    <span class="data-label">睡眠评分:</span>
                    <span class="data-value">${vitals.sleep_score || '--'}</span>
                </div>
            `;
        }
        
        function updateEnvironmentDisplay(env) {
            const container = document.getElementById('environment-data');
            container.innerHTML = `
                <div class="data-row">
                    <span class="data-label">温度:</span>
                    <span class="data-value">${env.temperature || '--'}°C</span>
                </div>
                <div class="data-row">
                    <span class="data-label">湿度:</span>
                    <span class="data-value">${env.humidity || '--'}%</span>
                </div>
                <div class="data-row">
                    <span class="data-label">亮度:</span>
                    <span class="data-value">${env.brightness || '--'}</span>
                </div>
                <div class="data-row">
                    <span class="data-label">噪音:</span>
                    <span class="data-value">${env.noise_level || '--'} dB</span>
                </div>
                <div class="data-row">
                    <span class="data-label">灯光:</span>
                    <span class="data-value">${env.light_switch ? '💡 开' : '🌙 关'}</span>
                </div>
            `;
        }
        
        function updateBedDisplay(bed) {
            const container = document.getElementById('bed-data');
            container.innerHTML = `
                <div class="data-row">
                    <span class="data-label">舵机角度:</span>
                    <span class="data-value">${bed.servo_angle || '--'}°</span>
                </div>
                <div class="data-row">
                    <span class="data-label">舵机速度:</span>
                    <span class="data-value">${bed.servo_speed || '--'}</span>
                </div>
                <div class="data-row">
                    <span class="data-label">加热等级:</span>
                    <span class="data-value">${bed.heat_level || '--'}</span>
                </div>
            `;
        }
        
        function updateSleepDisplay(sleep) {
            const container = document.getElementById('sleep-data');
            container.innerHTML = `
                <div class="data-row">
                    <span class="data-label">清醒时长:</span>
                    <span class="data-value">${sleep.wake_hours || '--'} 小时</span>
                </div>
                <div class="data-row">
                    <span class="data-label">浅睡时长:</span>
                    <span class="data-value">${sleep.light_sleep_hours || '--'} 小时</span>
                </div>
                <div class="data-row">
                    <span class="data-label">深睡时长:</span>
                    <span class="data-value">${sleep.deep_sleep_hours || '--'} 小时</span>
                </div>
                <div class="data-row">
                    <span class="data-label">睡眠标志:</span>
                    <span class="data-value">${sleep.sleep_flag || '--'}</span>
                </div>
            `;
        }
        
        function updateRawData(data) {
            document.getElementById('raw-data').textContent = JSON.stringify(data, null, 2);
        }
        
        function updateTimestamp() {
            const now = new Date();
            document.getElementById('timestamp').innerHTML = `
                🕐 最后更新: ${now.toLocaleString('zh-CN')}
            `;
        }
        
        function getHeartRateStatus(heartRate) {
            if (!heartRate) return '';
            if (heartRate >= 60 && heartRate <= 100) return 'status-good';
            if (heartRate >= 50 && heartRate <= 120) return 'status-warning';
            return 'status-error';
        }
        
        function getSleepStateText(state) {
            const states = {
                0: '清醒',
                1: '浅睡',
                2: '深睡',
                3: 'REM睡眠'
            };
            return states[state] || '--';
        }
        
        // 立即加载数据，然后每5秒更新一次
        fetchData();
        setInterval(fetchData, 5000);
        
        // 床板控制相关变量
        let currentAngle = 0;
        let currentSpeed = 2;
        
        // 初始化床板控制
        function initBedControl() {
            const angleSlider = document.getElementById('angle-slider');
            const angleDisplay = document.getElementById('angle-display');
            const speedButtons = document.querySelectorAll('.speed-btn');
            
            // 角度滑块事件
            angleSlider.addEventListener('input', function() {
                currentAngle = parseInt(this.value);
                angleDisplay.textContent = currentAngle;
            });
            
            // 速度按钮事件
            speedButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    speedButtons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentSpeed = parseInt(this.dataset.speed);
                });
            });
        }
        
        // 调整床板
        async function adjustBed() {
            updateConnectionStatus('connecting');
            
            try {
                const response = await fetch('/api/adjust-bed', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        angle: currentAngle,
                        speed_level: currentSpeed
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    updateConnectionStatus('connected');
                    showMessage('✅ ' + data.message, 'success');
                } else {
                    updateConnectionStatus('disconnected');
                    showMessage('❌ ' + data.message, 'error');
                }
            } catch (error) {
                updateConnectionStatus('disconnected');
                showMessage('❌ 网络错误: ' + error.message, 'error');
            }
        }
        
        // 复位床板
        async function resetBed() {
            document.getElementById('angle-slider').value = 0;
            document.getElementById('angle-display').textContent = '0';
            currentAngle = 0;
            currentSpeed = 2;
            
            // 重置速度按钮
            document.querySelectorAll('.speed-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.speed === '2') {
                    btn.classList.add('active');
                }
            });
            
            await adjustBed();
        }
        
        // 应用预设
        function applyPreset(angle, speed) {
            document.getElementById('angle-slider').value = angle;
            document.getElementById('angle-display').textContent = angle;
            currentAngle = angle;
            currentSpeed = speed;
            
            // 更新速度按钮
            document.querySelectorAll('.speed-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.speed === speed.toString()) {
                    btn.classList.add('active');
                }
            });
            
            adjustBed();
        }
        
        // 更新连接状态
        function updateConnectionStatus(status) {
            const indicator = document.getElementById('connection-status');
            const text = document.getElementById('connection-text');
            
            indicator.className = 'status-indicator status-' + status;
            
            switch (status) {
                case 'connected':
                    text.textContent = '已连接';
                    break;
                case 'connecting':
                    text.textContent = '连接中...';
                    break;
                default:
                    text.textContent = '未连接';
            }
        }
        
        // 显示消息
        function showMessage(message, type) {
            // 创建消息元素
            const messageDiv = document.createElement('div');
            messageDiv.style.position = 'fixed';
            messageDiv.style.top = '20px';
            messageDiv.style.right = '20px';
            messageDiv.style.padding = '15px';
            messageDiv.style.borderRadius = '8px';
            messageDiv.style.color = 'white';
            messageDiv.style.fontWeight = 'bold';
            messageDiv.style.zIndex = '9999';
            messageDiv.style.boxShadow = '0 4px 8px rgba(0,0,0,0.3)';
            messageDiv.textContent = message;
            
            if (type === 'success') {
                messageDiv.style.background = '#00b894';
            } else {
                messageDiv.style.background = '#e17055';
            }
            
            document.body.appendChild(messageDiv);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 3000);
        }
        
        // 初始化床板控制
        setTimeout(initBedControl, 100);
    </script>
</body>
</html>
    """)

if __name__ == '__main__':
    print("🛏️ 健康床系统启动中...")
    
    # 初始化设备
    initialize_devices()
    
    # 启动数据收集线程
    data_thread = threading.Thread(target=collect_data, daemon=True)
    data_thread.start()
    print("📊 数据收集线程已启动")
    
    print("🌐 Web界面将在 http://127.0.0.1:5000 启动")
    print("📊 系统准备就绪，开始监控...")
    
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
